/** 地理定位相关服务 */
export * as GeoLocUtil from './geolocation'

/**
 * 根据页面参数生成跳转路由地址
 * @param url
 * @param query
 */
export const getUrlByQuery = (url: string, query = {}) => {
    if (query) {
        url += url.includes('?') ? '&' : '?';
        Object.keys(query).forEach((key) => {
            url += `${key}=${Reflect.get(query, key)}&`;
        });
        url = url.slice(0, url.length - 1);
    }
    return url;
};

/** 生成唯一uuid */
export const uuid = (function () {
    let d = new Date().getTime();
    const uid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
        /[xy]/g,
        function (c) {
            const r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
        }
    );
    return uid;
})();

/**
 * 防抖
 * @param callback
 * @param wait
 */
export function debounce(callback: Function, wait: number) {
    let time: any = null;
    return function () {
        clearTimeout(time);
        time = setTimeout(() => {
            // eslint-disable-next-line prefer-rest-params
            callback(null, arguments);
        }, wait);
    };
}

/**
 * 节流
 * @param callback
 * @param delay
 */
export function throttle(callback: Function, delay: number) {
    let previous = 0;
    return function () {
        const now = +new Date();
        if (now - previous > delay) {
            // eslint-disable-next-line prefer-rest-params
            callback(null, arguments);
            previous = now;
        }
    };
}

/**
 * @description 去除空
 * @param values
 */
export function convertValues(values: { [key: string]: any }): {
    [key: string]: any;
} {
    const entity = { ...values };
    Object.entries(entity).forEach(([key, val]) => {
        if (val === "" || val === undefined || val === null) {
            delete entity[key];
        }
    });
    return entity;
}

/** 获取系统窗口尺寸参数 */
export function getWindowSize(): Promise<UniApp.GetSystemInfoResult | null> {
    return new Promise((resolve) => {
        uni.getSystemInfo({
            success(system) {
                resolve({ ...system })
            },
            fail() { resolve(null) }
        })
    })
}